from sqlalchemy import Column, Integer, String, Boolean, DateTime, JSON, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from .base import Base

class Strategy(Base):
    """
    量化交易策略模型
    """
    __tablename__ = "strategies"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    name = Column(String(100), nullable=False, unique=True, comment='策略名称')
    description = Column(String(500), nullable=True, comment='策略描述')
    code = Column(String(50), nullable=False, unique=True, comment='策略唯一代码')
    is_active = Column(Boolean, default=True, comment='是否激活')
    parameters = Column(JSON, nullable=True, comment='策略参数，JSON格式')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联交易记录
    trades = relationship("Trade", back_populates="strategy")
    
    def __repr__(self):
        return f"<Strategy(name='{self.name}', code='{self.code}')>"


class Trade(Base):
    """
    交易记录模型
    """
    __tablename__ = "trades"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    strategy_id = Column(Integer, ForeignKey("strategies.id"), nullable=False, comment='策略ID')
    symbol = Column(String(20), nullable=False, comment='交易对符号')
    direction = Column(String(10), nullable=False, comment='方向: long/short')
    entry_price = Column(String(30), nullable=False, comment='开仓价格')
    entry_time = Column(DateTime, nullable=False, comment='开仓时间')
    exit_price = Column(String(30), nullable=True, comment='平仓价格')
    exit_time = Column(DateTime, nullable=True, comment='平仓时间')
    volume = Column(String(30), nullable=False, comment='交易数量')
    profit = Column(String(30), nullable=True, comment='盈亏金额')
    status = Column(String(20), default="open", comment='状态: open/closed')
    signal_data = Column(JSON, nullable=True, comment='开平仓信号数据')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联策略
    strategy = relationship("Strategy", back_populates="trades")
    
    def __repr__(self):
        return f"<Trade(symbol='{self.symbol}', direction='{self.direction}', status='{self.status}')>" 